import React from "react";
import {
  Col,
  Input,
  Select,
  Button,
  Form,
  Upload,
  Tooltip,
  Divider,
  Spin,
  message,
  Avatar,
} from "antd";
import { QuestionCircleOutlined, UploadOutlined } from "@ant-design/icons";
import "./personalCenter.css";
// import { Link, Router, Route, NavLink } from "react-router-dom";
import {
  _getCodeList,
  _updateUserInfo,
  _updateAvatar,
} from "../../util/api/user/index";

const { Option } = Select;
const url = require("../../util/conUrl");

function beforeUpload(file) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
}
class PersonalCenter extends React.Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      userData: null,
      codeList: [],
      user_img: "",
      user_id: null,
      isshow: false,
      isLoading: false,
    };
    this.handleChange = this.handleChange.bind(this);
  }
  UNSAFE_componentWillMount() {
    let b_user = JSON.parse(localStorage.getItem("b_user"));
    let c_user = JSON.parse(localStorage.getItem("c_user"));
    console.log("sb", b_user);
    if (b_user && c_user) {
      this.setState({
        userData: b_user,
        user_img: c_user.user_img,
        user_id: c_user.user_id,
      });
    }
    _getCodeList().then((res) => {
      // console.log(res.data.data);
      this.setState({ codeList: res.data.data });
    });
  }
  componentDidMount = () => {
    //    let userData = JSON.parse(localStorage.getItem("user"));
    //    if (userData) {
    //      this.setState({
    //        userData: userData,
    //        user_img: userData.user_img,
    //      });
    //    }
  };
  handleMenuClick = (e) => {
    console.log("click ", e);
    this.setState({
      current: e.key,
    });
  };
  onFinish = (data) => {
    console.log("Received values of form: ", data);
    this.setState({ isLoading: true });
    this.formRef.current.resetFields();
    this.formRef.current.setFieldsValue(data);
    _updateUserInfo(this.state.user_id, data)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          localStorage.setItem("b_user", JSON.stringify(data));
          this.setState({ isLoading: false, isshow: false });
          message.success("更新成功");
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  formChange = (e) => {
    if (!this.state.isshow) {
      this.setState({ isshow: true });
    }
    return;
  };
  handleChange = (info) => {
    let self = this;
    if (info.file.status === "uploading") {
      // this.setState({ loading: true });
      return;
    }
    if (info.file.status === "done") {
      let c_user = JSON.parse(localStorage.getItem("c_user"));

      let temp = {
        user_img: info.file.response.data.data.filename,
      };
      setTimeout(() => {
        _updateAvatar(c_user.user_id, temp).then((res) => {
          if (res.status === 200 && res.data.code === 0) {
            self.setState({
              user_img: info.file.response.data.data.filename,
            });
            c_user.user_img = info.file.response.data.data.filename;
            localStorage.setItem("c_user", JSON.stringify(c_user));

            message.success("更新成功");
          }
        });
      }, 1500);
    }
  };
  render() {
    const layout = {
      labelCol: {
        span: 7,
      },
      wrapperCol: {
        span: 15,
      },
    };
    const tailLayout = {
      wrapperCol: {
        offset: 7,
        span: 15,
      },
    };
    let userData = this.state.userData;
    return (
      <div style={{ width: "100%", display: "flex" }}>
        <Col span={13}>
          <div>
            <div style={{ textAlign: "center", width: "100%" }}>
              <h3>基本信息设置</h3>
            </div>
            <Divider></Divider>
            <Spin tip="Loading..." spinning={this.state.isLoading}>
              <Form
                {...layout}
                ref={this.formRef}
                name="control-ref"
                onFinish={this.onFinish}
                scrollToFirstError
                initialValues={{
                  user_email: userData.user_email,
                  user_git: userData.user_git,
                  user_name: userData.user_name,
                  user_cname: userData.user_cname,
                  user_study_dir: userData.user_study_dir,
                  user_grade: userData.user_grade,
                  user_gender: userData.user_gender,
                  user_type: userData.user_type,
                  user_code_id: userData.user_code_id,
                  user_work: userData.user_work,
                }}
                onValuesChange={this.formChange}
              >
                <Form.Item
                  name="user_email"
                  label="邮箱"
                  rules={[
                    {
                      type: "email",
                      message: "该邮箱格式无效!",
                    },
                    {
                      required: true,
                      message: "邮箱不能为空!",
                    },
                  ]}
                >
                  <Input placeholder="邮箱" allowClear />
                </Form.Item>
                <Form.Item
                  name="user_git"
                  label="Git"
                  rules={[
                    {
                      required: true,
                      message: "Please input your Git!",
                    },
                  ]}
                >
                  <Input placeholder="Git地址, 没有填无" allowClear />
                </Form.Item>
                <Form.Item
                  name="user_name"
                  label="姓名"
                  rules={[
                    {
                      required: true,
                      message: "请填写你的姓名！",
                    },
                  ]}
                >
                  <Input placeholder="姓名" />
                </Form.Item>
                {/* <Form.Item
                  name="user_cname"
                  label={
                    <span>
                      英文姓名&nbsp;
                      <Tooltip title="(例如：Xiangdong Su)">
                        <QuestionCircleOutlined />
                      </Tooltip>
                    </span>
                  }
                  rules={[
                    {
                      required: true,
                      message: "请填写你的英文姓名!",
                      whitespace: true,
                    },
                  ]}
                >
                  <Input
                    placeholder="英文姓名（例如：Xiangdong Su）"
                    allowClear
                  />
                </Form.Item> */}
                <Form.Item
                  name="user_gender"
                  label="性别"
                  rules={[
                    {
                      required: true,
                      message: "请选择性别!",
                    },
                  ]}
                >
                  <Select placeholder="性别" allowClear>
                    <Option value={0}>
                      <span role="img" aria-label="woman">
                        🚺♀
                      </span>
                    </Option>
                    <Option value={1}>
                      <span role="img" aria-label="male">
                        🚺♂
                      </span>
                    </Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name="user_study_dir"
                  label="方向"
                  rules={[
                    {
                      required: true,
                      message: "请选择你的研究方向!",
                    },
                  ]}
                >
                  <Select
                    placeholder="主研究方向"
                    allowClear
                    placeholder="研究方向"
                  >
                    <Option value="语音处理">语音处理</Option>
                    <Option value="计算机视觉">计算机视觉</Option>
                    <Option value="NLP">NLP</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  name="user_grade"
                  label="年级"
                  rules={[
                    {
                      required: true,
                      message: "请选择你的年级!",
                    },
                  ]}
                >
                  <Select placeholder="年级" allowClear placeholder="年级">
                    <Option value={4}>博士</Option>
                    <Option value={3}>研三</Option>
                    <Option value={2}>研二</Option>
                    <Option value={1}>研一</Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name="user_type"
                  label="学位"
                  rules={[
                    {
                      required: true,
                      message: "请选择你的学位!",
                    },
                  ]}
                >
                  <Select placeholder="学位" allowClear placeholder="学位">
                    <Option value="学">学硕</Option>
                    <Option value="专">专硕</Option>
                    <Option value="无">无</Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name="user_code_id"
                  label="状态"
                  rules={[
                    {
                      required: true,
                      message: "请选择你的状态!",
                    },
                  ]}
                >
                  <Select
                    placeholder="目前状态"
                    allowClear
                    placeholder="你目前状态"
                  >
                    {this.state.codeList.map((v) => (
                      <Option value={v.user_code_id}>{v.user_code_name}</Option>
                    ))}
                  </Select>
                </Form.Item>

                {/* <Form.Item name="user_work" label="公司">
                  <Input placeholder="实习或就业填写,其他情况无需填写" />
                </Form.Item> */}

                {this.state.isshow ? (
                  <Form.Item {...tailLayout}>
                    <Button
                      type="primary"
                      htmlType="submit"
                      className="login-form-button"
                    >
                      更新基本信息
                    </Button>
                  </Form.Item>
                ) : null}
              </Form>
            </Spin>
          </div>
        </Col>
        <Col span={1}></Col>
        <Col span={8}>
          <div>
            <div style={{ textAlign: "center", width: "100%" }}>
              <h3>头像设置</h3>
            </div>
            <Divider></Divider>
            <div className="pc-avavar">
              <Avatar
                size={120}
                src={url.api + "/file/avatar/" + this.state.user_img}
              ></Avatar>
              <Upload
                name="file"
                action="/api/up_avatar"
                beforeUpload={beforeUpload}
                onChange={this.handleChange}
                showUploadList={false}
                accept="image/png, image/jpeg"
              >
                <Button>
                  <UploadOutlined /> 上传头像
                </Button>
              </Upload>
            </div>
          </div>
        </Col>
      </div>
    );
  }
}

export default PersonalCenter;
